package org;

import com.sun.org.apache.regexp.internal.RE;
import javafx.concurrent.Task;

import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * Created by yangshunxing on 2017/6/30.
 */
public class ReadWriteLockDemo extends HashMap {

    private ReadWriteLock lock = new ReentrantReadWriteLock();

    @Override
    public Object get(Object key) {
//        lock.readLock().lock();
//        Object value = super.get(key);
//        lock.readLock().unlock();
//        return value;
        return super.get(key);
    }

    public static void main(String[] args) {
        ReadWriteLockDemo map = new ReadWriteLockDemo();
        for (int i=0;i<100000;i++){
            map.put("key"+i,"value"+i);
        }
        Map map1 = new HashMap();
        for (int i=0;i<100000;i++){
            map1.put("key"+i,"value"+i);
        }
        ExecutorService threadPool = Executors.newCachedThreadPool();
        Collection tasks = null;
        Long startTime = null;
        for (int j = 0; j<100000; j++){
            if (j==0) startTime = System.currentTimeMillis();
            threadPool.execute(new ReadLockThread(map, j));
        }
        try {
            threadPool.invokeAll(tasks);
        } catch (NullPointerException e) {
            System.out.println("加锁查询用时"+(System.currentTimeMillis()-startTime));
        }catch (Exception e){
            e.printStackTrace();
        }

        threadPool.shutdown();
       /* ExecutorService threadPool1 = Executors.newCachedThreadPool();
        for (int j = 0; j<100000; j++){
            if (j==0) startTime = System.currentTimeMillis();
            threadPool1.execute(new ReadLockThread(map, j));
        }
        try {
            threadPool1.invokeAll(tasks);
        } catch (NullPointerException e) {
            System.out.println("不加锁查询用时"+(System.currentTimeMillis()-startTime));
        }catch (Exception e){
            e.printStackTrace();
        }
        threadPool1.shutdown();*/

    }
}
